<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="灵感名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入灵感名" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable @change="handleQuery">
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:inspiration:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:inspiration:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:inspiration:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspirationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="灵感名" align="center" prop="name" />
      <el-table-column label="图片" align="center" prop="url">
        <template #default="scope">
          <el-image v-if="scope.row.url" :src="scope.row.url" :preview-src-list="[scope.row.url]" preview-teleported
            fit="cover" style="width: 80px; height: 80px; border-radius: 5px;" hide-on-click-modal />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.state == 1" type="success">上架</el-tag>
          <el-tag v-else-if="scope.row.state == 0" type="danger">下架</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="230">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:inspiration:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:inspiration:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改灵感对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="inspirationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="灵感名" prop="name">
          <el-input v-model="form.name" placeholder="请输入灵感名" />
        </el-form-item>
        <el-form-item label="图片路径" prop="url">
          <image-upload v-model="form.url" :limit="1" @uploaded="handlePosterUploaded" list-type="picture" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择状态" clearable>
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Inspiration">
import {
  listInspiration,
  getInspiration,
  delInspiration,
  addInspiration,
  updateInspiration,
} from "@/api/customerService/inspiration";

const { proxy } = getCurrentInstance();

const inspirationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const inspirationRef = ref(); // 新增表单引用
const isEdit = ref(false); // 新增编辑状态标识

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    url: null,
    description: null,
    state: "1",
    isDelete: null,
  },
  rules: {
    // 新增表单验证规则
    name: [{ required: true, message: "灵感名不能为空", trigger: "blur" }],
    state: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  listInspiration(queryParams.value).then((response) => {
    inspirationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    url: null,
    description: null,
    state: null,
    createTime: null,
    updateTime: null,
    isDelete: null,
  };
  if (inspirationRef.value) {
    inspirationRef.value.resetFields();
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  isEdit.value = false;
  reset();
  open.value = true;
  title.value = "添加灵感";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const _id = row.id || ids.value[0];
  if (!_id) {
    proxy.$modal.msgWarning("请选择要修改的数据");
    return;
  }
  isEdit.value = true;
  reset();
  getInspiration(_id).then((response) => {
    form.value = response.data;
    // 处理图片URL格式，确保与上传组件兼容
    if (form.value.url) {
      // 如果是字符串格式，转换为上传组件需要的数组格式
      if (typeof form.value.url === "string") {
        form.value.url = [{ url: form.value.url }];
      }
    }
    // 确保状态是字符串类型，匹配下拉框
    if (form.value.state !== undefined && form.value.state !== null) {
      form.value.state = form.value.state.toString();
    }
    open.value = true;
    title.value = "修改灵感";
  });
}
/** 处理图片上传后的URL */
function handlePosterUploaded(url) {
  form.value.url = url;
}

/** 提交按钮 */
function submitForm() {
  inspirationRef.value.validate((valid) => {
    if (valid) {
      // 处理表单数据，确保图片URL格式正确
      const submitData = { ...form.value };

      // 处理图片URL - 从上传组件获取正确格式
      if (submitData.url && Array.isArray(submitData.url)) {
        if (submitData.url.length > 0) {
          submitData.url = submitData.url[0].url || submitData.url[0];
        } else {
          submitData.url = null;
        }
      } else if (
        submitData.url &&
        typeof submitData.url === "object" &&
        submitData.url.url
      ) {
        submitData.url = submitData.url.url;
      }

      // 状态转为数字类型
      submitData.state = submitData.state ? Number(submitData.state) : 0;

      if (isEdit.value) {
        // 编辑操作使用FormData格式
        const formData = new FormData();
        
        // 将灵感数据转换为JSON字符串
        const inspirationData = { ...submitData };
        formData.append(
          "inspiration",
          new Blob([JSON.stringify(inspirationData)], {
            type: "application/json",
          })
        );

        // 添加图片文件（如果存在）
        if (
          form.value.url &&
          Array.isArray(form.value.url) &&
          form.value.url.length > 0
        ) {
          const fileObj = form.value.url[0];
          if (fileObj.raw) {
            formData.append("file", fileObj.raw);
          }
        } else if (
          form.value.url &&
          typeof form.value.url === "object" &&
          form.value.url.raw
        ) {
          formData.append("file", form.value.url.raw);
        }

        // 使用与新增相同的FormData方式更新
        updateInspiration(formData)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          })
          .catch((err) => {
            console.error("修改失败", err);
            proxy.$modal.msgError("修改失败");
          });
      } else {
        // 新增操作使用FormData格式
        const formData = new FormData();

        // 将灵感数据转换为JSON字符串
        const inspirationData = { ...submitData };
        formData.append(
          "inspiration",
          new Blob([JSON.stringify(inspirationData)], {
            type: "application/json",
          })
        );

        // 添加图片文件
        if (
          form.value.url &&
          Array.isArray(form.value.url) &&
          form.value.url.length > 0
        ) {
          const fileObj = form.value.url[0];
          if (fileObj.raw) {
            formData.append("file", fileObj.raw);
          }
        } else if (
          form.value.url &&
          typeof form.value.url === "object" &&
          form.value.url.raw
        ) {
          formData.append("file", form.value.url.raw);
        }

        addInspiration(formData)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          })
          .catch((err) => {
            console.error("新增失败", err);
            proxy.$modal.msgError("新增失败");
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除灵感编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delInspiration(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function handleDetail(row) {
  proxy.$router.push({
    path: `/customer/inspiration/detail/${row.id}`,
  });
}

getList();
</script>
